//
//  JYUtils.m
//  FpdCarInCube
//
//  Created by WXC on 2017/4/11.
//  Copyright © 2017年 jiaoyin. All rights reserved.
//

#import "JYUtils.h"
#import "NSDate+YYAdd.h"
#import "sys/utsname.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import<CommonCrypto/CommonDigest.h>

@implementation JYUtils


// 获取某年某月总共多少天
+ (NSInteger)getDaysInMonth:(NSInteger)year month:(NSInteger)imonth
{
    // imonth == 0的情况是应对在CourseViewController里month-1的情况
    if((imonth == 0)||(imonth == 1)||(imonth == 3)||(imonth == 5)||(imonth == 7)||(imonth == 8)||(imonth == 10)||(imonth == 12))
        return 31;
    if((imonth == 4)||(imonth == 6)||(imonth == 9)||(imonth == 11))
        return 30;
    if((year%4 == 1)||(year%4 == 2)||(year%4 == 3))
    {
        return 28;
    }
    if(year%400 == 0)
        return 29;
    if(year%100 == 0)
        return 28;
    return 29;
}


// 是否 空字典或空数组
+ (BOOL)isBlankObject:(id)object
{
    if (!(object && [object respondsToSelector:@selector(count)]))
    {
        return YES;
    }
    
    BOOL ret = YES;
    if (object && ![object isKindOfClass:[NSNull class]] && [object count] > 0)
    {
        ret = NO;
    }
    
    return ret;
}

/********************* 目录 **********************/
// 创建目录，如果不存在，则创建
+ (BOOL)createDirectory:(NSString *)dirName
{
    BOOL isCreated = NO;
    
    if (dirName && dirName.length > 0)
    {
        BOOL isDir = NO;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL existed = [fileManager fileExistsAtPath:dirName isDirectory:&isDir];
        
        if (!(isDir == YES && existed == YES))
        {
            isCreated = [fileManager createDirectoryAtPath:dirName withIntermediateDirectories:YES attributes:nil error:nil];
            
            if (isCreated)
            {
                JYLog(@"创建目录成功\n%@\n",dirName);
            }
            else
            {
                JYLog(@"创建目录失败");
            }
        }
        else
        {
            isCreated = YES;
            JYLog(@"该目录已经存在\n%@\n",dirName);
        }
    }
    else
    {
        JYLog(@"目录名为空");
    }
    
    return isCreated;
}



+ (void)reminderInfoWithView:(UIView *)view
{
    CGFloat width = 200;
    CGFloat height = 50;
    NSString *text = @"";
    CGRect rect = CGRectZero;
    text = @"已经加载全部数据";
    rect = CGRectMake((view.xmg_width - width)/2, view.xmg_height - height - 10, width, height);
    UILabel *label = [[UILabel alloc] init];
    label.text = text;
    label.font = [UIFont systemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor lightGrayColor];
    label.frame = rect;
    label.alpha = 0.0;
    label.layer.cornerRadius = 5;
    label.clipsToBounds = YES;
    [view.window addSubview:label];
    
    [UIView animateWithDuration:1.0 animations:^{
        label.alpha = 1;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1.0 delay:1.0 options:UIViewAnimationOptionCurveLinear animations:^{
            label.alpha = 0.0;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
    
}

+ (void)reminderInfoWithString:(NSString *)string andRect:(CGRect)rect andColor:(UIColor *)color
{
    
    UILabel *label = [[UILabel alloc] initWithFrame:rect];
    label.text = string;
    label.font = [UIFont systemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = color;
    label.alpha = 0.0;
    label.layer.cornerRadius = 5;
    label.clipsToBounds = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:label];
    label.center = [UIApplication sharedApplication].keyWindow.center;
    [UIView animateWithDuration:0.1 animations:^{
        label.alpha = 1;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 delay:2.0 options:UIViewAnimationOptionCurveLinear animations:^{
            label.alpha = 0.0;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
    
}

+ (NSString *)getDateByAddingDays:(NSInteger)days andDateString:(NSString *)dateString
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [[dateFormatter dateFromString:dateString] dateByAddingDays:days];
    NSString *endDate = [dateFormatter stringFromDate:date];
    return endDate;
}

+ (NSString *)getDateByAddingMonths:(NSInteger)months andDateString:(NSString *)dateString
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM"];
    NSDate *date = [[dateFormatter dateFromString:dateString] dateByAddingMonths:months];
    NSString *endDate = [dateFormatter stringFromDate:date];
    return endDate;
}

/**
 *  返回当天时分秒
 *
 *  @return <#return value description#>
 */
+ (NSString *)getToday
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *today = [dateFormatter stringFromDate:[NSDate date]];
    return today;
}

/**
 *  返回当天时分秒
 *
 *  @return <#return value description#>
 */
+ (NSString *)getTodayDateAndHourMinuteSecond
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *today = [dateFormatter stringFromDate:[NSDate date]];
    return today;
}

// 计算普通文字的size
+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

// 获取app版本号，并转换成整数
+ (NSInteger)getAppVersion
{
    NSString *appVersion = [[[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"] stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSInteger version = [appVersion integerValue];
    return version;
}


+ (void)setTagsWithAPNsInfos:(NSArray *)APNsInfos andEnvironment:(NSString *)environment andIsLogin:(BOOL)isLogin
{
//    NSMutableSet *setM = [NSMutableSet set];
//    for (JYAPNSSettingModel *model in APNsInfos) {
//        if (model.IsSupport) {
//            NSString *setUnit = [NSString stringWithFormat:@"AlertType_%zi",model.AlertType];
//            [setM addObject:setUnit];
//        }
//    }
//    NSNumber *OID = [[[JYOAuthAccount sharedJYOAuthAccount].Data safeObjectForKey:@"CurUserInfo"] safeObjectForKey:@"OID"];
//    NSInteger oid = [OID integerValue];
//    NSString *setOidUnit = [NSString stringWithFormat:@"OID_%zi",oid];
//    [setM addObject:setOidUnit];
//    if (isLogin) {
//        [setM addObject:@"Login"];
//    }
//    else
//    {
//        [JYUtils logOut];
//    }
//    [setM addObject:environment];
//    [JPUSHService setTags:setM alias:nil fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
//        JYLog(@"%@",iAlias);
//        JYLog(@"%@",iTags);
//        
//    }];
}



+ (BOOL)isEarlierThanTimeNowWithTime:(NSString *)compareTime andLastday:(NSString *)lastDay
{
    NSInteger lastDayNum = [[lastDay stringByReplacingOccurrencesOfString:@"-" withString:@""] integerValue];
    NSInteger compareTimeNum = [[compareTime stringByReplacingOccurrencesOfString:@"-" withString:@""] integerValue];
    if (compareTimeNum < lastDayNum) {
        return YES;
    }
    return NO;
}


+ (NSString *)date2StringWithDate:(NSDate *)date dateFormat:(NSString *)fmt
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:fmt];
    NSString *dateStr = [dateFormatter stringFromDate:date];
    
    return dateStr;
}

+ (NSString *)dateStrByAddDot:(NSString *)dateStr
{
    if (!(dateStr.length)) return nil;
    NSString *sub1 = [dateStr substringWithRange:NSMakeRange(0, 4)];
    NSString *sub2 = [dateStr substringWithRange:NSMakeRange(4, 2)];
    NSString *sub3 = [dateStr substringWithRange:NSMakeRange(6, 2)];
    return [NSString stringWithFormat:@"%@.%@.%@",sub1,sub2,sub3];
}


/**
 *    @brief    string转换成date
 *
 *    @param     dateString   日期string
 *    @param     fmt          @"yyyy-MM-dd HH:mm:ss"、 @"yyyy-MM-dd"
 *
 *    @return    日期Date
 */
+ (NSDate *)dateFromString:(NSString *)dateString formatter:(NSString *)fmt
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:fmt];
    return [dateFormatter dateFromString:dateString];
}

#pragma mark - 限制编辑框(含英文、中文)输入长度
// 限制中文输入长度
+ (NSString *)textFiledEditChanged:(UITextField *)textField andLimitCount:(NSInteger)length
{
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"])
    { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (toBeString.length > length)
            {
                textField.text = [toBeString substringToIndex:length];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else
        {
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else
    {
        if (toBeString.length > length)
        {
            textField.text = [toBeString substringToIndex:length];
        }
    }
    
    return textField.text;
}

// 限制中文输入长度
+ (NSString *)textViewEditChanged:(UITextView *)textField andLimitCount:(NSInteger)length
{
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"])
    { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (toBeString.length > length)
            {
                textField.text = [toBeString substringToIndex:length];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else
        {
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else
    {
        if (toBeString.length > length)
        {
            textField.text = [toBeString substringToIndex:length];
        }
    }
    
    return textField.text;
}


+ (UIImage *)captureWithView:(UIView *)view
{
    // 1.开启上下文
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
    
    // 2.将控制器view的layer渲染到上下文
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    // 3.取出图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 4.结束上下文
    UIGraphicsEndImageContext();
    return newImage;
}


+ (NSString*)disable_EmojiString:(NSString *)text
{
    //去除表情规则
    //  \u0020-\\u007E  标点符号，大小写字母，数字
    //  \u00A0-\\u00BE  特殊标点  (¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾)
    //  \u2E80-\\uA4CF  繁简中文,日文，韩文 彝族文字
    //  \uF900-\\uFAFF  部分汉字
    //  \uFE30-\\uFE4F  特殊标点(︴︵︶︷︸︹)
    //  \uFF00-\\uFFEF  日文  (ｵｶｷｸｹｺｻ)
    //  \u2000-\\u201f  特殊字符(‐‑‒–—―‖‗‘’‚‛“”„‟)
    // 注：对照表 http://blog.csdn.net/hherima/article/details/9045765
    
    NSRegularExpression* expression = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString* result = [expression stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, text.length) withTemplate:@""];
    
    return result;
}


// 检测手机号格式是否正确
+ (BOOL)checkMobilephoneNumber:(NSString *)phoneNumber
{
    if ([phoneNumber length] > 0)
    {
        NSString *reg = @"^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|16[0|1|2|3|4|5|6|7|8|9]|17[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|4|5|6|7|8|9]|19[0|1|2|3|4|5|6|7|8|9])\\d{8}$";
        NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
        BOOL res1 = [regextestmobile evaluateWithObject:phoneNumber];
        if (res1)
        {
            return YES;
        }
        else
        {
             [ShowInfoView showMessage:@"请输入正确的手机号"];
            return NO;
        }
    }
    else
    {
        [ShowInfoView showMessage:@"请输入您的手机号"];
    }
    
    return NO;
}

// 检验身份证是否正确
+ (BOOL)checkIDCard:(NSString *)IDCard
{
    if (IDCard.length > 0)
    {
        NSString *regex = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        BOOL isMatch = [predicate evaluateWithObject:IDCard];
        if (isMatch)
        {
            return YES;
        }
        else
        {
            [ShowInfoView showMessage:@"请输入正确的身份证号"];
            return NO;
        }
    }
    else
    {
        [ShowInfoView showMessage:@"请输入身份证号"];
        return NO;
    }
    
}

// 设备
+ (NSString*)deviceString
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G (A1203)";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G (A1241/A1324)";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS (A1303/A1325)";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (A1349)";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S (A1387/A1431)";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (A1456/A1532)";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,3"]) return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7_PLUS";
    if ([platform isEqualToString:@"iPhone9,4"]) return @"iPhone 7_PLUS";
    
    if ([platform isEqualToString:@"Phone10,1"]) return @"iPhone 8";
    if ([platform isEqualToString:@"iPhone10,4"]) return @"iPhone 8";
    if ([platform isEqualToString:@"iPhone10,2"]) return @"iPhone 8 Plus";
    if ([platform isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus";
    
    if ([platform isEqualToString:@"iPhone10,3"]) return @"iPhone X";
    if ([platform isEqualToString:@"iPhone10,6"]) return @"iPhone X";
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    
    JYLog(@"NOTE: Unknown device type: %@", platform);
    return @"未知设备型号";
}


+ (NSString *)md5:(NSString *)input {
    
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)(strlen(cStr)), digest ); // This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return  output;
}

@end
